package com.TechMahindra.wx.utils;

/**
 * Created by weican on 2017/8/18.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @ClassName PropertiesUtil.java
 * @Description 系统配置工具类
 * @author weican
 */
public class PropertiesUtil {
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private static ConcurrentHashMap<String, Properties> proMap = new ConcurrentHashMap<>();

    /**
     * 根据key从qywx.properties配置文件获取配置信息
     *
     * @param key 键值
     * @return
     */
    public static String getValue(String key) {
        return getValue(key, null);
    }

    /**
     * 根据key从gzt.properties配置文件获取配置信息
     *
     * @param key          键值
     * @param defaultValue 默认值
     * @return
     */
    public static String getValue(String key, String defaultValue) {
        return getValue("qywx.properties", key, defaultValue);
    }

    /**
     * 从配置文件中获取对应key值
     *
     * @param fileName     配置文件名
     * @param key          key值
     * @param defaultValue 默认值
     * @return
     */
    public static String getValue(String fileName, String key, String defaultValue) {
        String val = null;
        Properties properties = proMap.get(fileName);
        if (properties == null) {
            InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
            try {
                properties = new Properties();
                properties.load(new InputStreamReader(inputStream, "UTF-8"));
                proMap.put(fileName, properties);
                val = properties.getProperty(key, defaultValue);
            } catch (IOException e) {
                logger.error("in params{}{}{}" , fileName, key, defaultValue);
                logger.error("getValue", e);
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e1) {
                    logger.error(e1.toString());
                }
            }
        } else {
            val = properties.getProperty(key, defaultValue);
        }
        return val;
    }
}